package com.xszx.utils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;

public class BusinessBatchGenerator {
    private static final AtomicInteger COUNTER = new AtomicInteger(0);
    private static final int MAX_SEQUENCE = 9999; // 最大序列号

    // 生成基于业务规则的批次号
    public static String generateByBusinessRule(String productType) {
        // 时间部分 (精确到天)
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String datePart = sdf.format(new Date());

        // 获取并递增序列号，使用循环确保原子性
        int seq;
        do {
            seq = COUNTER.get();
            // 当达到最大值时，尝试重置为0
            if (seq >= MAX_SEQUENCE) {
                if (COUNTER.compareAndSet(seq, 0)) {
                    break;
                }
            } else if (COUNTER.compareAndSet(seq, seq + 1)) {
                break;
            }
        } while (true);

        // 格式化为4位字符串
        String seqPart = String.format("%04d", seq);

        return productType + datePart + seqPart;
    }

    public static void main(String[] args) {
        // 测试不同产品类型
        System.out.println("批次号: " + generateByBusinessRule("FOOD"));  // 例如: FOOD000020230518
        System.out.println("批次号: " + generateByBusinessRule("ELEC"));  // 例如: ELEC202305180001
    }
}